package hot100;

public class sortList3 {
    public mergeKLists.ListNode sortList(mergeKLists.ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        mergeKLists.ListNode fast = head.next;
        mergeKLists.ListNode slow = head;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        mergeKLists.ListNode temp = slow.next;
        slow.next = null;
        mergeKLists.ListNode left = sortList(head);
        mergeKLists.ListNode right = sortList(temp);
        mergeKLists.ListNode h = new mergeKLists.ListNode(0);
        mergeKLists.ListNode ret = h;
        while(left != null && right != null) {
            if(left.val < right.val) {
                h.next = left;
                left = left.next;
            }else {
                h.next = right;
                right = right.next;
            }
            h = h.next;
        }
        if(left == null) {
            h.next = right;
        }else {
            h.next = left;
        }
        return ret.next;
    }
}
